﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace Antioch.Base
{
    [Jemgine.Engine.Node, Jemgine.Engine.Category("Antioch System")]
    public class SpawnPlayer : Jemgine.Data.ScriptNode
    {
        public string TemplateName { get; set; }
        public string EntityName { get; set; }
        public Vector2 InitialGravity { get; set; }

        [ContentSerializer(Optional = true)]
        public bool MakeCameraFocus { get; set; }

        public SpawnPlayer()
        {
            AddInput("Fire", null);
            InitialGravity = new Vector2(0, -160);
            MakeCameraFocus = true;
            AddOutput("Relay", null);
        }

        public override void FireTerminal(int InputID, Jemgine.Data.ScriptPayload Payload)
        {
            if (InputID == 0)
            {
                var GameState = Sim.GetModule<GameStateModule>();
                if (GameState == null) throw new InvalidOperationException(); //TODO : Exception for missing module.
                Jemgine.Data.EntityRecord PlayerEntity = null;

                Jemgine.Data.MapData Data = null;
                Sim.ImportMap(out Data, TemplateName, Position, false, (A) =>
                    {
                        Sim.DefaultElementHandler(A);
                        if (A is Jemgine.Data.EntityRecord && (A as Jemgine.Data.EntityRecord).Name == EntityName)
                            PlayerEntity = A as Jemgine.Data.EntityRecord;
                    });

                GameState.Player = PlayerEntity;

                if (MakeCameraFocus)
                {
                    Sim.CameraModule.Focus = PlayerEntity;
                    Sim.CameraModule.DestinationZoom = 8;
                }

                if (PlayerEntity != null)
                {
                    var Health = PlayerEntity.GetComponent<Health>();
                    if (Health != null)
                    {
                        Health.CurrentHealth = GameState.ActiveSaveState.PlayerHealth;
                        Health.MaxHealth = GameState.ActiveSaveState.MaxPlayerHealth;
                    }

                    PlayerEntity.Angle = Jemgine.Math.Vector.AngleBetweenVectors(new Vector2(0, -1), InitialGravity);
                    var Controller = PlayerEntity.GetComponent<PlayerControllerBase>();
                    if (Controller != null)
                        GameState.PushInputMode(new PlayerInputMode(Controller));

                    if (MakeCameraFocus)
                        Sim.CameraModule.TeleportCamera(-PlayerEntity.Position, 8, -PlayerEntity.Angle);

                }
            }

            OutputTerminals[0].Fire(Payload);
        }
    }
}
